import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class BookPanel extends JPanel {
    private JTable bookTable;
    private DefaultTableModel tableModel;
    private BookDAO bookDAO = new BookDAO();

    public BookPanel() {
        setLayout(new BorderLayout());

        // 创建顶部面板，包含搜索和添加按钮
        JPanel topPanel = new JPanel(new BorderLayout());
        JPanel searchPanel = new JPanel();
        JTextField searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        JButton addButton = new JButton("添加图书");

        searchPanel.add(new JLabel("图书标题/作者:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        topPanel.add(searchPanel, BorderLayout.WEST);
        topPanel.add(addButton, BorderLayout.EAST);

        // 创建表格
        String[] columnNames = {"ID", "ISBN", "标题", "作者", "出版社", "价格", "库存"};
        tableModel = new DefaultTableModel(columnNames, 0);
        bookTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(bookTable);

        // 创建底部面板，包含编辑和删除按钮
        JPanel bottomPanel = new JPanel();
        JButton editButton = new JButton("编辑图书");
        JButton deleteButton = new JButton("删除图书");
        JButton refreshButton = new JButton("刷新");

        bottomPanel.add(editButton);
        bottomPanel.add(deleteButton);
        bottomPanel.add(refreshButton);

        // 添加组件到面板
        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);

        // 初始化表格数据
        loadBooks();

        // 添加按钮事件监听器
        searchButton.addActionListener(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                searchBooks(keyword);
            } else {
                loadBooks();
            }
        });

        addButton.addActionListener(e -> showAddBookDialog());

        editButton.addActionListener(e -> {
            int selectedRow = bookTable.getSelectedRow();
            if (selectedRow != -1) {
                int bookId = (int) tableModel.getValueAt(selectedRow, 0);
                showEditBookDialog(bookId);
            } else {
                JOptionPane.showMessageDialog(BookPanel.this, "请先选择一本图书", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteButton.addActionListener(e -> {
            int selectedRow = bookTable.getSelectedRow();
            if (selectedRow != -1) {
                int bookId = (int) tableModel.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(BookPanel.this,
                        "确定要删除这本书吗?", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    if (bookDAO.deleteBook(bookId)) {
                        JOptionPane.showMessageDialog(BookPanel.this, "删除成功");
                        loadBooks();
                    } else {
                        JOptionPane.showMessageDialog(BookPanel.this, "删除失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(BookPanel.this, "请先选择一本图书", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        refreshButton.addActionListener(e -> loadBooks());
    }

    // 加载所有图书到表格
    private void loadBooks() {
        tableModel.setRowCount(0);
        List<Book> books = bookDAO.getAllBooks();
        for (Book book : books) {
            Object[] row = {
                    book.getId(),
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPublisher(),
                    book.getPrice(),
                    book.getStock()
            };
            tableModel.addRow(row);
        }
    }

    // 搜索图书
    private void searchBooks(String keyword) {
        tableModel.setRowCount(0);
        List<Book> books = bookDAO.searchBooks(keyword);
        for (Book book : books) {
            Object[] row = {
                    book.getId(),
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPublisher(),
                    book.getPrice(),
                    book.getStock()
            };
            tableModel.addRow(row);
        }
    }

    // 显示添加图书对话框
    private void showAddBookDialog() {
        JDialog dialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(this), "添加图书", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(7, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JTextField isbnField = new JTextField();
        JTextField titleField = new JTextField();
        JTextField authorField = new JTextField();
        JTextField publisherField = new JTextField();
        JTextField priceField = new JTextField();
        JTextField stockField = new JTextField();

        panel.add(new JLabel("ISBN:"));
        panel.add(isbnField);
        panel.add(new JLabel("标题:"));
        panel.add(titleField);
        panel.add(new JLabel("作者:"));
        panel.add(authorField);
        panel.add(new JLabel("出版社:"));
        panel.add(publisherField);
        panel.add(new JLabel("价格:"));
        panel.add(priceField);
        panel.add(new JLabel("库存:"));
        panel.add(stockField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String isbn = isbnField.getText().trim();
                String title = titleField.getText().trim();
                String author = authorField.getText().trim();
                String publisher = publisherField.getText().trim();
                double price = Double.parseDouble(priceField.getText().trim());
                int stock = Integer.parseInt(stockField.getText().trim());

                if (isbn.isEmpty() || title.isEmpty() || author.isEmpty() || publisher.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                Book book = new Book(isbn, title, author, publisher, price, stock);
                if (bookDAO.addBook(book)) {
                    JOptionPane.showMessageDialog(dialog, "添加成功");
                    dialog.dispose();
                    loadBooks();
                } else {
                    JOptionPane.showMessageDialog(dialog, "添加失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "价格和库存必须为数字", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "输入有误", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    // 显示编辑图书对话框
    private void showEditBookDialog(int bookId) {
        Book book = bookDAO.getBookById(bookId);
        if (book == null) {
            JOptionPane.showMessageDialog(this, "找不到图书", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(this), "编辑图书", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(7, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JTextField isbnField = new JTextField(book.getIsbn());
        JTextField titleField = new JTextField(book.getTitle());
        JTextField authorField = new JTextField(book.getAuthor());
        JTextField publisherField = new JTextField(book.getPublisher());
        JTextField priceField = new JTextField(String.valueOf(book.getPrice()));
        JTextField stockField = new JTextField(String.valueOf(book.getStock()));

        panel.add(new JLabel("ISBN:"));
        panel.add(isbnField);
        panel.add(new JLabel("标题:"));
        panel.add(titleField);
        panel.add(new JLabel("作者:"));
        panel.add(authorField);
        panel.add(new JLabel("出版社:"));
        panel.add(publisherField);
        panel.add(new JLabel("价格:"));
        panel.add(priceField);
        panel.add(new JLabel("库存:"));
        panel.add(stockField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String isbn = isbnField.getText().trim();
                String title = titleField.getText().trim();
                String author = authorField.getText().trim();
                String publisher = publisherField.getText().trim();
                double price = Double.parseDouble(priceField.getText().trim());
                int stock = Integer.parseInt(stockField.getText().trim());

                if (isbn.isEmpty() || title.isEmpty() || author.isEmpty() || publisher.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                book.setIsbn(isbn);
                book.setTitle(title);
                book.setAuthor(author);
                book.setPublisher(publisher);
                book.setPrice(price);
                book.setStock(stock);

                if (bookDAO.updateBook(book)) {
                    JOptionPane.showMessageDialog(dialog, "更新成功");
                    dialog.dispose();
                    loadBooks();
                } else {
                    JOptionPane.showMessageDialog(dialog, "更新失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "价格和库存必须为数字", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "输入有误", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }
}